﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Data.Entity;
using System.Globalization;
using System.ServiceModel;

namespace Elf.Data.Entity.Management
{
    /// <summary>
    /// Defines a scope wherein only one DbContext instance is created, and shared by all
    /// of those who use it. Instances of this class are supposed to be used in a using()
    /// statement.
    /// </summary>
    /// <typeparam name="TContext">An DbContext type.</typeparam>
    public class DbContextScope<TContext> : IDisposable where TContext : ContextBase, new()
    {
        [ThreadStatic]
        private static DbContextScope<TContext> _currentScope;
        private TContext _dbContext;
        private bool _isDisposed, _dbContextBelongsToOperationContext;

        /// <summary>
        /// Returns a reference to the DbContext that is created for the current scope. If
        /// no scope currently exists, null is returned.
        /// </summary>
        protected internal static TContext CurrentDbContext
        {
            get { return _currentScope != null ? _currentScope._dbContext : null; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DbContextScope&lt;TContext&gt;"/> class.
        /// </summary>
        public DbContextScope()
        {
            if (_currentScope != null && !_currentScope._isDisposed)
                throw new InvalidOperationException("Instances of this class cannot be nested.");

            _dbContextBelongsToOperationContext = OperationContext.Current != null;

            if (!_dbContextBelongsToOperationContext)
                _dbContext = new TContext();
            else
            {
                if (ApplicationRequestContext.Current.DbContext == null)
                {
                    ApplicationRequestContext.Current.DbContext = new TContext();
                }
                this._dbContext = ApplicationRequestContext.Current.DbContext as TContext;
            }
            Thread.BeginThreadAffinity();
            System.Diagnostics.Debug.WriteLine("Begin of DbContextScope");
            _currentScope = this;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_isDisposed)
                {
                    _isDisposed = true;
                    _currentScope = null;
                    Thread.EndThreadAffinity();

                    if (_dbContext != null && !_dbContextBelongsToOperationContext)
                    {
                        _dbContext.Dispose();
                    }

                    Debug.WriteLine("End of DbContextScope");
                }
            }
        }

        /// <summary>
        /// Commits all changes to the database.
        /// </summary>
        public virtual void Commit()
        {
            var count = _dbContext.SaveChanges();
            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0} objects saved to the database", count));
        }
    }
}
